package com.liufei.class02;

public class Code01_PreSum {

    /**
     * 给定一个数组，给定一个区间，求这个区间内数组的合
     */
    public static class RangeSum {
        // 前缀和
        private int[] arr;

        public RangeSum(int[] array) {
            arr = array;
        }

        public int rangeSum(int L, int R) {
            int sum = 0;
            for (int i = L; i <= R; i++) {
                sum += arr[i];
            }
            return sum;
        }
    }


    public static class RangeSum1 {
        // 前缀和
        private int[][] preSum;

        public RangeSum1(int[] array) {
            int N = array.length;
            // 只需要一个数组
            preSum = new int[N][N];
            for (int i = 0; i < N; i++) {
                preSum[i][i] = array[i];
                for (int j = i + 1; j < N; j++) {
                    preSum[i][j] = preSum[i][j - 1] + array[j];
                }
            }
        }

        public int rangeSum(int L, int R) {
            // 直接取当前二维数组的值即可
            return preSum[L][R];
        }
    }


    public static class RangeSum2 {
        // 前缀和
        private int[] preSum;

        public RangeSum2(int[] array) {
            int N = array.length;
            // 只需要一个数组
            preSum = new int[N];
            preSum[0] = array[0];
            for (int i = 1; i < N; i++) {
                preSum[i] = preSum[i - 1] + array[i];
            }
        }

        public int rangeSum(int L, int R) {
            return L == 0 ? preSum[R] : preSum[R] - preSum[L - 1];
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 2, 1, 4};

        RangeSum rangeSum = new RangeSum(arr);
        System.out.println(rangeSum.rangeSum(1, 3));

        RangeSum1 rangeSum1 = new RangeSum1(arr);
        System.out.println(rangeSum1.rangeSum(1, 3));

        RangeSum2 rangeSum2 = new RangeSum2(arr);
        System.out.println(rangeSum2.rangeSum(1, 3));
    }
}
